package com.hishop.service.impl;

import com.hishop.common.Constant;
import com.hishop.common.ServerResponse;
import com.hishop.common.TokenCache;
import com.hishop.dao.UserMapper;
import com.hishop.pojo.User;
import com.hishop.service.IUserService;
import com.hishop.util.MD5Util;
import com.hishop.util.RedisShardedPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * Created by hejie on 2017/7/14.
 */
@Service("iUserService")
@Slf4j
public class UserServiceImpl implements IUserService{
    @Autowired
    private UserMapper userMapper;

    @Override
    public ServerResponse<User> login(String username, String password) {
         int resultCount=userMapper.checkUsername(username);
        if(resultCount==0){
            return ServerResponse.createByErrorMessage(Constant.NO_USER);
        }
        //todo 密码登录MD5
        User user=userMapper.selectLogin(username,MD5Util.MD5EncodeUtf8(password));
        if (user==null){
            return ServerResponse.createByErrorMessage(Constant.PWD_ERROR);
        }

        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);
    }

    @Override
    public ServerResponse<String> register(User user) {
        ServerResponse<String> response=checkValid(user.getUsername(),Constant.USERNAME);
        if(!response.isSuccess()){
            return response;
        }
         response=checkValid(user.getEmail(),Constant.EMAIL);
        if (!response.isSuccess()){
            return  response;
        }
        user.setRole(Constant.Role.ROLE_CUSTOMER);
        //md5加密
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        if(userMapper.insert(user)==0){
            return ServerResponse.createByError(Constant.REGISTER_FAIL);
        }
        return ServerResponse.createBySuccessMessage(Constant.REGISTER_SUCCESS);
    }

    @Override
    public ServerResponse<String> checkValid(String str, String type) {
        if (StringUtils.isNotBlank(str)){
            if (Constant.USERNAME.equals(type)){
                int resultCount=userMapper.checkUsername(str);
                if(resultCount>0){
                    return ServerResponse.createByErrorMessage(Constant.HAVE_USER);
                }
            }
            if (Constant.EMAIL.equals(type)){
                if (userMapper.checkEmail(str)>0){
                    return  ServerResponse.createByErrorMessage(Constant.HAVE_EMAIL);
                }
            }
        }else{
            return ServerResponse.createByErrorMessage(Constant.ARG_ERROR);
        }
        return ServerResponse.createBySuccessMessage(Constant.CHECK_VALID_SUCCESS);
    }

    @Override
    public ServerResponse<String> checkAnswer(String username, String question, String answer) {
        int resultCount=userMapper.checkAnswer(username,question,answer);
        if(resultCount>0){
            String forgetToken= UUID.randomUUID().toString();
           // TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,forgetToken);
            RedisShardedPoolUtil.setEx(TokenCache.TOKEN_PREFIX+username,forgetToken,60*60*12);
            return ServerResponse.createBySuccess(forgetToken);
        }
        return ServerResponse.createByErrorMessage(Constant.QUESTION_ANSWER_ERROR);
    }

    @Override
    public ServerResponse<String> selectQuestion(String username) {
        if(checkValid(username,Constant.USERNAME).isSuccess()){
            return ServerResponse.createByErrorMessage(Constant.NO_USER);
        }
        String queston =  userMapper.selectQuestionByUsername(username);
        if (StringUtils.isNotBlank(queston)){
           return ServerResponse.createBySuccess(queston);
        }
        return ServerResponse.createByErrorMessage(Constant.QUESTION_BLANK);
    }

    @Override
    public ServerResponse<String> forgetResetPassword(String username, String passwordNew, String forgetToken) {
        if (StringUtils.isBlank(forgetToken)){
            return ServerResponse.createByErrorMessage(Constant.TOKEN_ARG_ERROR);
        }
        ServerResponse response = this.checkValid(username,Constant.USERNAME);
        if (response.isSuccess()){
            return ServerResponse.createByErrorMessage(Constant.NO_USER);
        }
        //String token= TokenCache.getKey(TokenCache.TOKEN_PREFIX+username);
        String token=RedisShardedPoolUtil.get(TokenCache.TOKEN_PREFIX+username);
        if(StringUtils.isBlank(token)){
            return ServerResponse.createByErrorMessage(Constant.TOKEN_EXPIRE);
        }
        if (StringUtils.equals(forgetToken,token)){
            String md5Password= MD5Util.MD5EncodeUtf8(passwordNew);
            int rowCount= userMapper.updatePasswordByUsername(username,md5Password);
            if (rowCount>0){
                return ServerResponse.createBySuccessMessage(Constant.UPDATE_PASSWORD_SUCCESS);
            }
        }else{
            return ServerResponse.createByErrorMessage(Constant.TOKEN_ERROR);
        }
        return ServerResponse.createByErrorMessage(Constant.UPDATE_PASSWORD_FAIL);
    }

    @Override
    public ServerResponse<String> resetPassword(String passwordOld, String passwordNew, User user) {
        //防止横向越权，要校验一下这个用户的旧密码，一定要指定是这个用户
        int resultCount=userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld),user.getId());
        if (resultCount==0){
            return ServerResponse.createByErrorMessage(Constant.PWD_ERROR);
        }
        user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
        int updateCount=userMapper.updateByPrimaryKeySelective(user);
        if (updateCount>0){
            return ServerResponse.createBySuccessMessage(Constant.PWD_UPDATE_SUCCESS);
        }
        return ServerResponse.createByErrorMessage(Constant.PWD_UPDATE_FAIL);
    }

    @Override
    public ServerResponse<User> updateUserInfo(User user) {
        //username不能更新  email校验是否存在
        int resultCount=userMapper.checkEmailByUserId(user.getEmail(),user.getId());
        if (resultCount>0){
          return ServerResponse.createByErrorMessage("email已存在，请更换email再尝试更新");
        }
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());
        int updateCount=userMapper.updateByPrimaryKeySelective(updateUser);
        if (updateCount>0){
           return ServerResponse.createBySuccess("更新个人信息成功",updateUser);
        }
        return ServerResponse.createByErrorMessage("更新个人信息失败");
    }

    @Override
    public ServerResponse<User> getUserInfo(Integer userId) {
        User user=userMapper.selectByPrimaryKey(userId);
        if (user== null){
            return ServerResponse.createByErrorMessage("找不到当前用户");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);
    }

    @Override
    public ServerResponse<String> checkAdminRole(User user) {
        if (user!=null&&user.getRole().intValue()==Constant.Role.ROLE_ADMIN){
               return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError();
    }
}
